package org.javascud.extensions.justtest;

import java.net.InetAddress;

public class IPAddressTester
{
    public static void maina(String[] args) throws Exception
    {
        System.out.println(InetAddress.getLocalHost().getHostAddress());
        System.out.println(InetAddress.getLocalHost().getCanonicalHostName());

        System.out.println(InetAddress.getByName("sohu.com").getHostAddress());
        System.out.println(InetAddress.getByName("sohu.com").getCanonicalHostName());


    }

    public static String getLocalHostIP()
    {
        String ip;
        try
        {
            InetAddress addr = InetAddress.getLocalHost();
            ip = addr.getHostAddress();
        }
        catch (Exception ex)
        {
            ip = "";
        }
        return ip;
    }

    public static String getLocalHostName()
    {
        String hostName;
        try
        {
            InetAddress addr = InetAddress.getLocalHost();
            hostName = addr.getHostName();
        }
        catch (Exception ex)
        {
            hostName = "";
        }
        return hostName;
    }

    public static String[] getAllLocalHostIP()
    {
        String[] ret = null;
        try
        {
            String hostName = getLocalHostName();
            if (hostName.length() > 0)
            {
                InetAddress[] addrs = InetAddress.getAllByName(hostName);
                if (addrs.length > 0)
                {
                    ret = new String[addrs.length];
                    for (int i = 0; i < addrs.length; i++)
                    {
                        ret[i] = addrs[i].getHostAddress();
                    }
                }
            }

        }
        catch (Exception ex)
        {
            ret = null;
        }
        return ret;
    }

    public static String[] getAllHostIPByName(String hostName)
    {
        String[] ret = null;
        try
        {
            if (hostName.length() > 0)
            {
                InetAddress[] addrs = InetAddress.getAllByName(hostName);
                if (addrs.length > 0)
                {
                    ret = new String[addrs.length];
                    for (int i = 0; i < addrs.length; i++)
                    {
                        ret[i] = addrs[i].getHostAddress();
                    }
                }
            }

        }
        catch (Exception ex)
        {
            ret = null;
        }
        return ret;
    }


    public static void main(String[] args)
    {
        //System.out.println(getLocalHostIP());
        System.out.println(" host name:" + getLocalHostName());

        String[] localIP = getAllLocalHostIP();
        for (int i = 0; i < localIP.length; i++)
        {
            System.out.println(localIP[i]);
        }
    }
}
